package com.ghck.server.bkcontroller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.exception.GhckException;
import com.ghck.server.utils.FileStoreUtil;
import com.ghck.shop.constant.GoodStatus;
import com.ghck.shop.model.Category;
import com.ghck.shop.model.GoodsImage;
import com.ghck.shop.model.request.GoodAddReq;
import com.ghck.shop.model.request.GoodsReq;
import com.ghck.shop.model.response.GoodsRes;
import com.ghck.shop.service.GoodsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/system/good")
@Api(description="管理员相关接口")
public class AdminGoodController {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(AdminGoodController.class);
	
	@Autowired
	private GoodsService goodsService;
	private static Logger logger = LoggerFactory.getLogger(AdminGoodController.class);
	
	
	@ApiOperation(value="进入添加商品页面")
	@RequestMapping(value="/addInit",method = RequestMethod.GET)
	public String addGoodInit(HttpServletRequest request){
		List<Category> list = goodsService.categoryList();
		request.setAttribute("categorys", list);
		return "back/good/add";
	}
	
	@ApiOperation(value="进入修改商品页面")
	@RequestMapping(value="/updateInit/{goodId}",method = RequestMethod.GET)
	public String updateInit(HttpServletRequest request,@PathVariable("goodId")Integer goodId){
		List<Category> list = goodsService.categoryList4Good();
		GoodsReq gr = new GoodsReq();
		gr.setId(goodId);
		GoodsRes goodsRes = goodsService.goodsDetail(gr);
		List<Category> checkCategoryList = goodsRes.getCategoryList();
		Set<Integer> set = categorySet(checkCategoryList);
		for(Category category:list){
			if(set.contains(category.getId())){
				category.setAddHot(1);
			}
		}
		request.setAttribute("categorys", list);
		request.setAttribute("good", goodsRes);
		return "back/good/update";
	}
	private Set<Integer> categorySet(List<Category> checkCategoryList){
		Set<Integer> set = new HashSet<Integer>();
		if(CollectionUtils.isNotEmpty(checkCategoryList)){
			for(Category category:checkCategoryList){
				set.add(category.getId());
			}
		}
		return set;
	}
	
	@ApiOperation(value="商品详情页")
	@RequestMapping(value="/detail/{goodId}",method = RequestMethod.GET)
	public String detail(HttpServletRequest request,@PathVariable("goodId")Integer goodId){
		GoodsReq gr = new GoodsReq();
		gr.setId(goodId);
		GoodsRes goodsRes = goodsService.goodsDetail(gr);
		LOGGER.info("++++++++{}",JSONObject.toJSONString(goodsRes));
		request.setAttribute("good", goodsRes);
		return "back/good/detail";
	}
	
	@ApiOperation(value="管理员修改商品")
	@RequestMapping(value="/update",method = RequestMethod.POST,consumes = "multipart/form-data")
	public String update(GoodAddReq goodAddReq,@RequestParam(value="files",required=false)MultipartFile[] files){
		LOGGER.info("good update info:{}", JSONObject.toJSONString(goodAddReq));
		if(StringUtils.isEmpty(goodAddReq.getTitle())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品名称不能为空");
			throw exception;
		}
		if(StringUtils.isEmpty(goodAddReq.getDescription())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品描述不能为空");
			throw exception;
		}
		if(goodAddReq.getSalePrice() == null || goodAddReq.getSalePrice() < 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"销售价格不能为空");
			throw exception;
		}
		if(goodAddReq.getMarketPrice() == null || goodAddReq.getMarketPrice() < 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"市场价格不能为空");
			throw exception;
		}
		if(files == null || files.length==0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品图片不能为空");
			throw exception;
		}
		if(CollectionUtils.isEmpty(goodAddReq.getCategoryList())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品分类不能为空");
			throw exception;
		}
		List<GoodsImage> goodsImageList = goodAddReq.getGoodsImageList();
		if(CollectionUtils.isEmpty(goodsImageList)){
			goodsImageList = new ArrayList<GoodsImage>();
		}
		GoodsImage goodsImage = null;
		if(files != null){
			for(MultipartFile file:files){
				if(StringUtils.isEmpty(file.getOriginalFilename())){
					continue;
				}
				goodsImage = new GoodsImage();
				String fileDbName = FileStoreUtil.storeFile(file, "shop/goods/");
				LOGGER.info("fileName:{}", fileDbName);
				goodsImage.setImageLarge(fileDbName);
				goodsImage.setImageSmall(fileDbName);
				goodsImage.setStatus(1);
				goodsImage.setSortOrder(0);
				goodsImage.setGoodsId(goodAddReq.getId());
				goodsImageList.add(goodsImage);
			}
		}
		
		//goodAddReq.setThumbnailImage(goodsImageList.get(0).getImageSmall());
		goodAddReq.setGoodsImageList(goodsImageList);
		goodsService.updateGood(goodAddReq);
		return "redirect:/system/good/list";
	}
	
	@ApiOperation(value="管理员添加商品")
	@RequestMapping(value="/add",method = RequestMethod.POST,consumes = "multipart/form-data")
	public String addGood(GoodAddReq goodAddReq,@RequestParam(value="files")MultipartFile[] files){
		LOGGER.info("request=>{}", JSONObject.toJSONString(goodAddReq));
		System.out.println(goodAddReq.getCategoryList().size());
		System.out.println(JSONObject.toJSONString(goodAddReq.getCategoryList()));
		if(StringUtils.isEmpty(goodAddReq.getTitle())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品名称不能为空");
			throw exception;
		}
		if(StringUtils.isEmpty(goodAddReq.getDescription())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品描述不能为空");
			throw exception;
		}
		if(goodAddReq.getSalePrice() == null || goodAddReq.getSalePrice() < 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"销售价格不能为空");
			throw exception;
		}
		if(goodAddReq.getMarketPrice() == null || goodAddReq.getMarketPrice() < 0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"市场价格不能为空");
			throw exception;
		}
		if(files == null || files.length==0){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品图片不能为空");
			throw exception;
		}
		if(CollectionUtils.isEmpty(goodAddReq.getCategoryList())){
			GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"商品分类不能为空");
			throw exception;
		}
		
		Integer isOnsale = goodAddReq.getIsOnsale();
		if(isOnsale != null){
			if(isOnsale != GoodStatus.init || isOnsale != GoodStatus.in_review){
				GhckException exception = new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(),"初始化商品状态只能是放入仓库或者提交审核");
				throw exception;
			}
		}else {
			goodAddReq.setIsOnsale(GoodStatus.init);
		}
		List<GoodsImage> goodsImageList = new ArrayList<GoodsImage>();
		GoodsImage goodsImage = null;
		for(MultipartFile file:files){
			goodsImage = new GoodsImage();
			String fileDbName = FileStoreUtil.storeFile(file, "shop/goods/");
			LOGGER.info("fileName:{}", fileDbName);
			goodsImage.setImageLarge(fileDbName);
			goodsImage.setImageSmall(fileDbName);
			goodsImage.setStatus(1);
			goodsImage.setSortOrder(0);
			goodsImageList.add(goodsImage);
		}
		goodAddReq.setThumbnailImage(goodsImageList.get(0).getImageSmall());
		goodAddReq.setGoodsImageList(goodsImageList);
		goodAddReq.setSupplierId(0);
		goodsService.addGood(goodAddReq);
		return "back/good/add_success";
	}
	/**
	 * 商品列表
	 * @param goodReq
	 * @return
	 */
	@ApiOperation(value="管理员商品列表")
	@RequestMapping(value="/list")
	public String managerList(GoodsReq goodsReq,HttpServletRequest request,
			Integer currentPage,
			Integer pageSize){
		goodsReq.setCurrentPage(currentPage);
		goodsReq.setPageSize(pageSize);
		if(goodsReq.getIsOnsale() != null ){
			if((goodsReq.getIsOnsale().intValue() + 100) == 0 ){
				goodsReq.setIsOnsale(null);
			}
		}
//		Page<GoodsRes> page  = goodsService.managerListPage(goodsReq);
		List<GoodsRes> list  = goodsService.managerListPage(goodsReq);
		request.setAttribute("list", list);
		List<Category> categoryList = goodsService.categoryListLevel();
		request.setAttribute("categoryList", categoryList);
		request.setAttribute("goodsReq", goodsReq);
		return "back/good/goods_list";
	}
	/**
	 * 审核通过
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/reviewGoodSuccess/{goodId}")
	public String reviewGoodSuccess(@PathVariable("goodId")Integer goodId){
		goodsService.reviewSuccGoodAdmin(goodId);
		return "redirect:/system/good/list";
	}
	/**
	 * 审核失败
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/reviewGoodFail/{goodId}")
	public String reviewGoodFail(@PathVariable("goodId")Integer goodId){
		goodsService.reviewFailGoodAdmin(goodId);
		return "redirect:/system/good/list";
	}
	/**
	 * 删除商品
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/delete/{goodId}")
	public String deleteGood(@PathVariable("goodId")Integer goodId){
		goodsService.deleteGoodAdmin(goodId);
		return "redirect:/system/good/list";
	}
	/**
	 * 上架商品
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/shelves/{goodId}")
	public String shelves(@PathVariable("goodId")Integer goodId){
		goodsService.shelvesGoodAdmin(goodId);
		return "redirect:/system/good/list";
	}
	/**
	 * 下架商品
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/xiajia/{goodId}")
	public String xiajia(@PathVariable("goodId")Integer goodId){
		goodsService.xiajiaGoodAdmin(goodId);
		return "redirect:/system/good/list";
	}
	
	/**
	 * 添加到首页 限时特惠 或 聚划算
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/marketingActivity/add/{goodId}/{marketingActivityId}")
	public String addMarketingActivity(@PathVariable("goodId")Integer goodId,@PathVariable("marketingActivityId")Integer marketingActivityId){
		goodsService.addMarketingActivity(goodId, marketingActivityId);
		return "redirect:/system/good/list";
	}
	
	/**
	 * 从首页 限时特惠 或 聚划算 中删除
	 * @param goodId
	 * @return
	 */
	@RequestMapping(value="/marketingActivity/delete/{goodId}/{marketingActivityId}")
	public String deleteMarketingActivity(@PathVariable("goodId")Integer goodId,@PathVariable("marketingActivityId")Integer marketingActivityId){
		goodsService.deleteMarketingActivity(goodId, marketingActivityId);
		return "redirect:/system/good/list";
	}
}